<template>
    <view class="container">
        <uni-segmented-control :current="currentIndex" :values="items" style-type="text" active-color="#007aff"
            @clickItem="onClickItem" />
        <view v-if="currentIndex === 0">
            <view style="padding-top: 10px;"></view>
            <uni-forms ref="baseForm" :modelValue="liuzhuanForm" labelPosition="left" border labelWidth="100px">
                <view style="padding-top: 10px;"></view>
                <uni-forms-item label="会议时间" required>
                    <uni-datetime-picker @click="chuanci()" @change="chuanci2" @maskClick="chuanci2()" type="datetime"
                        return-type="string" v-model="liuzhuanForm.meetingTime" />
                </uni-forms-item>
                <uni-forms-item label="会议地点" required>
                    <uni-easyinput type="text" v-model="liuzhuanForm.meetingPlace" />
                </uni-forms-item>
                <uni-forms-item label="会议主题" required>
                    <uni-easyinput type="text" v-model="liuzhuanForm.meetingTheme" />
                </uni-forms-item>

                <uni-forms-item label="会议交办事项">
                    <uni-easyinput type="textarea" v-model="liuzhuanForm.meetingMatter" />
                </uni-forms-item>

                <uni-forms-item label="落实情况">
                    <uni-easyinput type="textarea" v-model="liuzhuanForm.meetingWorkable" />
                </uni-forms-item>
                <!-- 附件模块 -->
                <uni-forms-item label="上传会议纪要" style="height: 80rpx;margin-top: 120rpx; position: relative;">
                    <lsj-upload v-show="liuzhuanForm.meetingUrl.length == 0"
                        style="position:absolute !important;  z-index: 10; !important" ref="lsjUpload" childId="upload1"
                        :size="uploadconfig3.size" :instantly="uploadconfig3.instantly" :formats="uploadconfig3.formats"
                        :option="option" @change="onChange" @uploadEnd="onuploadEnd" @fail="failFile">
                        <view style="width: 100%;text-align: right;color: #0b847b;" @click="fuckyou">
                            <i class="iconfont icon-24gf-folderOpen" style="color: #0b847b;"></i>
                            上传
                        </view>
                    </lsj-upload>
                </uni-forms-item>
                <view v-if="liuzhuanForm.meetingUrl.length">
                    <view class="file_list" v-for="(item, index) in liuzhuanForm.meetingUrl" :key="index">
                        <!--  @click="prevFileClick(item.url, item.name)" -->

                        <view style="display: flex; align-items: center; color: #0b847b">
                            <view @click="prevFileClick(item)" class="file_list_item">
                                <view>
                                    <i class="iconfont icon-24gf-folderOpen" style="color: #0b847b"></i>
                                    {{ item.name }}
                                </view>
                            </view>
                            <view class="iconfont icon-close" style="color: #e86565;margin-left:5px"
                                @click="delFile(index)"></view>
                        </view>
                    </view>
                </view>

                <view style="padding-top: 30px;"></view>
                <button type="primary" @click="clickApply">提交</button>
            </uni-forms>
        </view>

        <!-- ------------------------------------------------uni.getStorageSync("userInfo").uid -->
        <view v-if="currentIndex === 1">
            <view class="tops">
                <view style="margin-bottom:15px">
                    <button @click="clickSelectOne" class="btn-add" v-if="users.length != 0">{{ users[0].name }}</button>
                </view>
                <view style="margin-bottom:15px">
                    <button @click="clickSelectOne" class="btn-add" v-if="users.length == 0">{{ '选择查询人员' }}</button>
                </view>
                <picker mode="date" fields="month" :value="keyword" @change="search" style="height: 18px;" start="1990-01"
                    end="2050-09">
                    <uni-row>
                        <uni-col :span="12">
                            <view class="text-left">查询日期</view>
                        </uni-col>
                        <uni-col :span="12">
                            <view class="text-right">{{ keyword }}
                                <uni-icons type="calendar-filled"> </uni-icons>
                            </view>
                        </uni-col>
                    </uni-row>
                </picker>
            </view>
            <view v-for="(item, idx) in applyRecord" style="padding-bottom: 10px;" :key="idx">
                <!-- {{item}} -->
                <view class="card" @click="seeDetail(idx)">
                    <view class="card-body">
                        <view>会议主题：{{ item.meetingTheme }}</view>
                    </view>
                    <view class="card-footer">
                        <uni-row>
                            <uni-col :span="12">
                                <view class="card-footer-left">{{ item.createBy }}</view>
                            </uni-col>
                            <uni-col :span="12">
                                <view class="card-footer-right">{{ getFormatedTimeStr(item.createTime,
                                    "YYYY-MM-DD HH:mm:ss") }}
                                </view>
                            </uni-col>
                        </uni-row>
                    </view>
                </view>
            </view>
            <uni-load-more :status="moreStatus"></uni-load-more>
        </view>
    </view>
</template>
    
<script>
import moment from "moment";
import { websock } from "../../net/websock";
import {
    prevFile // 预览文件
} from "../../utils/preview.js";
import { addhuiyifankui, gethuiyifankuiList } from "../../net/huiyifankui";//

import { uploadconfig3 } from "../../const";

export default {
    data() {
        return {
            // 上传参数部分没有事情不要乱动
            uploadconfig3,
            option: {
                url: uploadconfig3.url,
                name: "file",
                header: { Authorization: uni.getStorageSync("token"), platform: 'APP' },
                formData: {}
            },
            total: 1, //当前页
            users: [],
            pageSize: 10,
            pageNum: 1,
            formats: uploadconfig3.formats,
            instantly: uploadconfig3.instantly,
            size: uploadconfig3.size,
            // files: new Map(),
            // 上传参数部分没有事情不要乱动
            items: ["发起提交", "历史数据"],
            currentIndex: 0,
            typeIndex: 0,
            attenders: [],//陪同人员
            userInfo: '',
            moreStatus: "more",
            applyRecord: [],
            keyword: "",
            suffix: "",
            files: new Map(),
            liuzhuanForm: {
                meetingTime: "",//会议时间
                meetingPlace: "",//会议地点
                meetingTheme: '',//会议主题
                meetingMatter: "",//会议交办事项
                meetingWorkable: "",//会议落实情况
                meetingUrl: [],//上传会议纪要附件
                userId: '',//
                auditors: []
            }
        };
    },
    async onLoad() {
        try {
            this.userInfo = await websock.getUserInfo();
            console.log("user info", this.userInfo);
        } catch (err) {
            console.error(err);
        }
    },
    async onReady() {
        // this.getNewestRecord();
    },
    // 下拉刷新，获取最新的数据
    onPullDownRefresh() {
        if (this.currentIndex == 0) {
            uni.stopPullDownRefresh();
        } else {
            this.pageNum = 1;
            this.applyRecord = [];
            this.getNewestRecord();
        }
    },
    // 上拉刷新，获取历史数据
    onReachBottom() {
        if (this.currentIndex == 1) {
            if (this.moreStatus == "more") {
                uni.showLoading({
                    title: "加载中"
                });
                this.pageNum += 1;
                this.getOlderRecord();
            }
        }
    },
    methods: {
        //选择查询人员
        clickSelectOne() {
            uni.navigateTo({
                url:
                    "/pages/common/contactSelect?selectedUsers=" +
                    JSON.stringify(this.users || []) +
                    "&isSingle=1",
                events: {
                    contactList: data => {
                        console.log("select peitong", data);
                        this.users = data.contactList;
                        this.pageNum = 1
                        this.pageSize = 10
                        this.applyRecord = [];
                        this.getNewestRecord();
                    }
                }
            });
        },
        //选择陪同人员
        clickSelectAttender() {
            uni.navigateTo({
                url: '/pages/common/contactSelect?selectedUsers=' + JSON.stringify(this.attenders || []),
                events: {
                    contactList: data => {
                        console.log('select auditor', data)
                        this.attenders = data.contactList
                        let arr = []
                        data.contactList.forEach(item => {
                            arr.push(item.uid)
                        })
                        console.log(arr.join(','));
                        this.liuzhuanForm.accompanyIds = arr.join(',')
                    }
                }
            })
        },


        // 预览上传的文件
        prevFileClick(url, name) {
            prevFile(url, name);
        },
        // 删除附件
        delFile() {
            for (let i = 0; i < this.liuzhuanForm.meetingUrl.length; i++) {
                this.liuzhuanForm.meetingUrl.splice(i, 1);
            }
            this.fuckyou();
        },
        // 附件上传恶心的代码块-------------------------------------------------------------
        // 某文件上传结束回调(成功失败都回调)
        onuploadEnd(item) {
            console.log(item);
            // let files = new Map();
            let res = JSON.parse(item.responseText);
            uni.hideLoading();
            if (res.code === 0) {
                console.log(res);
                this.liuzhuanForm.meetingUrl.push({
                    url: res.data.url,
                    name: res.data.fileName
                });
                this.suffix = res.data.suffix;
            }
            this.$forceUpdate();
        },
        // 文件选择回调
        onChange(files) {
            uni.showLoading({
                title: "上传中……"
            });
            this.files = files; // 更新选择的文件
            this.$forceUpdate(); // 强制更新视图
        },
        failFile() {
            uni.hideLoading();
        },
        // 穿刺一击让他们的遮罩层消失
        chuanci() {
            this.$refs.lsjUpload && this.$refs.lsjUpload.hide();
        },
        // 穿刺一击让他们的遮罩层消失
        chuanci2() {
            this.$refs.lsjUpload && this.$refs.lsjUpload.show();
            this.$forceUpdate();
        },
        // 强制重置附件按钮,万一出意外点2次按钮至少可以进去
        fuckyou() {
            this.$refs.lsjUpload && this.$refs.lsjUpload.hide();
            this.$refs.lsjUpload && this.$refs.lsjUpload.show();
            this.$forceUpdate();
        },
        // 附件上传恶心的代码块-------------------------------------------------------------
        // 获取最新的通知
        async getNewestRecord() {
            try {
                if (this.applyRecord.length == 0) {
                    let res = await gethuiyifankuiList({
                        userId: this.users.length !== 0 ? this.users[0].uid : '',
                        pageNum: this.pageNum,
                        pageSize: 10,
                        meetingTime: this.keyword
                    });
                    uni.hideLoading();
                    uni.stopPullDownRefresh();
                    this.total = res.total;
                    this.applyRecord = [...res.data, ...this.applyRecord];
                } else {
                    let res = await gethuiyifankuiList({
                        userId: this.users.length !== 0 ? this.users[0].uid : '',
                        pageNum: this.pageNum,
                        pageSize: 10,
                        meetingTime: this.keyword
                    });
                    uni.hideLoading();
                    uni.stopPullDownRefresh();
                    this.applyRecord = [...res.data, ...this.applyRecord];
                }
            } catch (e) {
                console.log(e);
            }
        },
        // 获取老的数据
        async getOlderRecord() {
            this.moreStatus = "loading";
            try {
                if (this.applyRecord.length == 0) {
                    let res = await gethuiyifankuiList({
                        userId: this.users.length !== 0 ? this.users[0].uid : '',
                        pageNum: this.pageNum,
                        pageSize: this.pageSize,
                        meetingTime: this.keyword
                    });

                    this.applyRecord = this.applyRecord.concat(res.data);
                    if (res.data.length < 10) {
                        this.moreStatus = "noMore";
                    } else {
                        this.moreStatus = "more";
                    }
                } else {
                    let res = await gethuiyifankuiList({
                        userId: this.users.length !== 0 ? this.users[0].uid : '',
                        pageNum: this.pageNum,
                        pageSize: this.pageSize,
                        meetingTime: this.keyword
                    });

                    this.applyRecord = this.applyRecord.concat(res.data);
                    if (res.data.length < 10) {
                        this.moreStatus = "noMore";
                    } else {
                        this.moreStatus = "more";
                    }
                }
            } catch (e) {
                uni.showToast({
                    title: e.message
                });
            }
        },

        onClickItem(e) {
            console.log(e);
            if (this.currentIndex !== e.currentIndex) {
                this.currentIndex = e.currentIndex;
                if (this.currentIndex == 1) {
                    this.applyRecord = [];
                    this.getNewestRecord();
                }
            }
        },
        // 获取格式化时间字符串
        getFormatedTimeStr(stamp, str = "MM-DD HH:mm:ss") {
            return moment(stamp).format(str);
        },
        async clickApply() {
            if (!this.liuzhuanForm.meetingTime)
                return uni.showToast({
                    title: "请选择会议时间",
                    icon: "none"
                });
            if (!this.liuzhuanForm.meetingTheme)
                return uni.showToast({
                    title: "请填写会议主题",
                    icon: "none"
                });
            if (!this.liuzhuanForm.meetingPlace)
                return uni.showToast({
                    title: "请填写会议地点",
                    icon: "none"
                });
            const tbMeetingFeedbackNotes = {
                userId: this.userInfo.uid,
                createBy: this.userInfo.name,
                // deptId: this.userInfo.department,
                meetingTime: this.liuzhuanForm.meetingTime,
                meetingTheme: this.liuzhuanForm.meetingTheme,
                meetingPlace: this.liuzhuanForm.meetingPlace,
                meetingMatter: this.liuzhuanForm.meetingMatter,
                meetingWorkable: this.liuzhuanForm.meetingWorkable,
                meetingUrl: JSON.stringify(this.liuzhuanForm.meetingUrl) || '',
            };
            console.log(tbMeetingFeedbackNotes);
            try {
                await addhuiyifankui(tbMeetingFeedbackNotes);
                setTimeout(
                    // () =>
                    //     uni.navigateBack({
                    //         delta: 1
                    //     }),
                    uni.showToast({
                        title: "操作成功",
                        icon: "success"
                    }),
                    1000
                );
                this.liuzhuanForm = {
                    meetingTime: "",//会议时间
                    meetingPlace: "",//会议地点
                    meetingTheme: '',//会议主题
                    meetingMatter: "",//会议交办事项
                    meetingWorkable: "",//会议落实情况
                    meetingUrl: [],//上传会议纪要附件
                    auditors: []
                };

                this.currentIndex = 1;
                this.applyRecord = [];
                this.getNewestRecord();
            } catch (err) {
                uni.showToast({
                    title: err.message || "error"
                });
            }

        },
        seeDetail(idx) {
            console.log(idx);
            uni.navigateTo({
                url: `/pages/task/huiyifankuiDetail?content=${this.applyRecord[idx].id
                    }`
            });
        },
        search(e) {
            console.log(e);
            this.keyword = e.detail.value
            this.applyRecord = [];
            this.pageNum = 1
            this.pageSize = 10
            this.getNewestRecord();
        }
    }
};
</script>
    
<style>
@import "../common/common.css";

/* 封面上传控件 */
::v-deep .file-picker__box {
    position: absolute !important;
    right: 0 !important;
    width: 200rpx !important;
    height: 132rpx !important;
}

::v-deep .file-picker__box-content {
    border: none !important;
}

.tops {
    margin: 15px 0
}

.text-right {
    font-size: 14px;
    padding-right: 10px;
    text-align: right;
}

.text-left {
    font-size: 14px;
    padding-left: 10px;
    text-align: left;
}
</style>
    